﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using Chenglin.WPMyStep.Controls;

namespace Chenglin.WPMyStep
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            // Load the main UI of the page
            ApplicationState state = ApplicationState.State;
            // state.LocationConsent = false;
            if (!state.LocationConsent.IsTrue())
            {
                // by default, we'll display a confirmation page to the user to let him decide
                // whether he could offer us the ability to access location service.
                //
                allowButton.Click += delegate
                {
                    state.LocationConsent = true;
                    state.Save();

                    ReplaceUI(new TrackControl { Page = this }, true);
                };
                declineButton.Click += delegate { ReplaceUI(new DeclinedControl(), true); };
            }
            else
            {
                // The user already granted us the permission to visit location service.
                //
                ReplaceUI(new TrackControl { Page = this }, false);
            }
        }

        private void ReplaceUI(UserControl control, bool deferRendering)
        {
            // create a new pivot item, and add it to the main container
            //
            PivotItem newPivotItem = new PivotItem { Content = control };
            newPivotItem.Margin = new Thickness(0, -10, 0, 0);

            if (deferRendering)
            {
                this.mainPivot.Items.Add(newPivotItem);

                // display the new pivot item in a new thread so that we can obvserve a animated page transition.
                //
                var timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromTicks(1);
                timer.Tick += delegate
                {
                    // stop the timer
                    timer.Stop();

                    // switch to the new pivot item on UI thread.
                    Dispatcher.BeginInvoke(() =>
                    {
                        this.mainPivot.SelectedItem = newPivotItem;
                        this.mainPivot.Items.Remove(pageOne);
                    });
                };
                timer.Start();
            }
            else
            {
                this.mainPivot.Items.Clear();
                this.mainPivot.Items.Add(newPivotItem);
            }
        }
    }
}